package com.abei.gas.service.Impl;

import com.abei.gas.entity.Card;
import com.abei.gas.entity.Device;
import com.abei.gas.entity.Payorder;
import com.abei.gas.mapper.CardMapper;
import com.abei.gas.mapper.DeviceMapper;
import com.abei.gas.mapper.PayorderMapper;
import com.abei.gas.service.PayorderService;
import com.abei.gas.vo.DataVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class PayorderServiceImpl extends ServiceImpl<PayorderMapper, Payorder> implements PayorderService {
    @Resource
    private PayorderMapper payorderMapper;
    @Resource
    private CardMapper cardMapper;

    @Override
    public DataVo<Payorder> findAll(Integer page, Integer limit) {
        List<Payorder> c=payorderMapper.selectList(null);
        DataVo<Payorder> datavo=new DataVo<>();
        datavo.setCode(0);
        datavo.setMsg("");
        IPage<Payorder> cardpage=new Page<>(page,limit);
        IPage<Payorder> result=payorderMapper.selectPage(cardpage,null);
        datavo.setCount(result.getTotal());
        c=result.getRecords();
        datavo.setData(c);
        return datavo;
    }

    @Override
    public DataVo<Payorder> findById(String number) {
        QueryWrapper<Payorder> u = new QueryWrapper<>();
        u.like("id",number);
        List<Payorder> cardList=payorderMapper.selectList(u);
        DataVo<Payorder> dataVO=new DataVo<>();
        dataVO.setCode(0);
        dataVO.setMsg("");
        Integer num = payorderMapper.selectCount(null);
        dataVO.setCount(Long.valueOf(num));
        dataVO.setData(cardList);
        return dataVO;
    }

    @Override
    public DataVo pay(Payorder payorder) {
        QueryWrapper<Card> cardQueryWrapper = new QueryWrapper<>();
        cardQueryWrapper.eq("id",payorder.getCardid());
        List<Card> cardList = cardMapper.selectList(cardQueryWrapper);
        if(cardList.size()==0){
            return DataVo.error(1,"卡不存在");
        }

        payorderMapper.insert(payorder);
        Card card=cardMapper.selectOne(cardQueryWrapper);
        //设置余额
        card.setBalance(card.getBalance()+payorder.getSum());
        //设置燃气余量
        card.setRest(card.getRest()+payorder.getGassum());

        cardMapper.updateById(card);
        return DataVo.success();
    }
}
